<template>
  <transition name="messageFade">
    <div
      :class="[`${classPrefix}`,type && `${classPrefix}--${type}`,background && `${classPrefix}--background`]"
      :style="expandStyle"
      v-show="visible"
      @mouseenter="clearTimer"
      @mouseleave="startTimer"
    >
      <Icon
        v-if="iconName"
        :name="iconName"
        :class="[ `${classPrefix}__icon`,type === 'loading' && `animation-rotate`,]"
      ></Icon>
      <span :class="[`${classPrefix}__content`]" v-html="content"></span>
      <Icon v-if="closable" name="close" :class="[`${classPrefix}__icon-closable`]" @click="close"></Icon>
    </div>
  </transition>
</template>

<script>
import Config from "/src/config";
import Icon from "/src/components/icon";
export default {
  name: "Message",
  data() {
    return {
      classPrefix: Config.classPrefix + "-message",
      visible: false,
      type: "info",
      content: "",
      duration: 2000,
      top: 40,
      currentPosition: 40,
      timer: null,
      closed: false,
      background: false,
      closable: false,
    };
  },
  computed: {
    iconName() {
      let result;
      switch (this.type) {
        case "info":
          result = "snapchatLogo";
          break;
        case "success":
          result = "smiley";
          break;
        case "warning":
          result = "smileyNervous";
          break;
        case "error":
          result = "smileySad";
          break;
        case "loading":
          result = "loading";
          break;
        default:
          result = "sunHorizon";
          break;
      }
      return result;
    },
    expandStyle() {
      return { top: parseFloat(this.currentPosition) + "px" };
    },
  },
  components: {
    Icon,
  },
  methods: {
    show() {
      this.visible = true;
      this.startTimer();
    },
    close() {
      this.closed = true;
      this.visible = false;
      this.onCloseComputed();
      this.onClose();
    },
    onClose() {},
    onCloseComputed() {},
    startTimer() {
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          !this.closed && this.close();
        }, this.duration);
      }
    },
    clearTimer() {
      this.timer && clearTimeout(this.timer);
    },
    handleAfterLeave() {
      this.clearTimer();
      this.$el.parentNode.removeChild(this.$el);
    },
  },
  beforeDestroy() {},
};
</script>
